<script setup>
import { ref, computed } from 'vue'
import { AddTaskService } from '@/api/task.js'
// , GetSourceTaskService
import { useUserStore } from '@/stores/modules/user'
import { GetNodeByName } from '@/api/node.js'
import { Delete } from '@element-plus/icons-vue'
import axios from 'axios'

const dialogVisible = ref(false)
const useStore = useUserStore()

// 节点信息
const nodeInfo = ref({})

// 优先级列表
const priorityOptions = ref([
  { label: '1（最高）', value: 1 },
  { label: 2, value: 2 },
  { label: 3, value: 3 },
  { label: 4, value: 4 },
  { label: 5, value: 5 },
  { label: 6, value: 6 },
  { label: 7, value: 7 },
  { label: 8, value: 8 },
  { label: 9, value: 9 },
  { label: '10（最低）', value: 10 }
])
// 获取路径传参的数据
const props = defineProps({
  algType: String
})
const list = ref('')
const formModel = ref({
  nodeId: -1,
  id: '',
  algType: props.algType,
  priority: '',
  lists: []
})

// 获取选择的节点信息
const initNode = async () => {
  const {
    data: { data }
  } = await GetNodeByName(useStore.getNodeName())
  nodeInfo.value = { ...data }

  // 初始化表单配置
  formModel.value.nodeId = nodeInfo.value.id
}

const btnMsg = ref('确认添加')
const title = ref('新增任务')
const open = (type) => {
  initNode()
  formModel.value.algType = type
  // 任务有限级默认设置为 5
  formModel.value.priority = 5
  dialogVisible.value = true
}

const emit = defineEmits(['success'])
// 提交任务信息
const onSubmit = async () => {
  if (!formModel.value.priority || !formModel.value.lists) {
    ElMessage.error('请填写 优先级 和输入数据源')
    return // 提前返回，避免后续处理
  }
  formModel.value.algType = formModel.value.algType
    ? formModel.value.algType
    : '暂无'

  await AddTaskService(formModel.value)
  ElMessage.success('添加成功')
  dialogVisible.value = false
  formModel.value.lists = []
  btnMsg.value = '确认添加'
  title.value = '新增任务'
  emit('success')
}
// 模型上传
const dialog = ref(true)
const isInput = ref(true)

// 模型上传
const import_Data = (item) => {
  let formData = new FormData()
  formData.append('file', item.file)
  formData.append('priority', formModel.value.priority)
  formData.append('nodeId', formModel.value.nodeId)
  formData.append('algType', formModel.value.algType)
  axios({
    method: 'post',
    url: 'http://62.234.16.239:8085/task/create/file',
    data: formData
  })
    .then((res) => {
      if (res.data.code == 200) {
        dialog.value = false
        dialogVisible.value = false
        ElMessage.success('上传成功')
        formModel.value.priority = ''
      }
    })
    .catch((error) => {
      console.error(error) // 打印错误信息，方便调试
      ElMessage.error('上传失败，请检查所上传信息')
      formModel.value.priority = ''
    })
}

const fanme = ref()
const before_Upload = (file) => {
  fanme.value = file.name
  if (!formModel.value.priority) {
    ElMessage.error('请填写 优先级 ')
    return // 提前返回，避免后续处理
  }
}
const successUpload = (res) => {
  if (res.code == 200) {
    dialog.value = false
    dialogVisible.value = false
    ElMessage.success('上传成功')
  } else if (res.code == 201) {
    // dialog.value = false
    dialogVisible.value = false
    ElMessage.error(res.message)
  }
}
const change = () => {
  dialog.value = !dialog.value
}
// 弹窗
const onAddItem = () => {
  isInput.value = false
}
// 添加数据源本地
const onAdd = () => {
  if (list.value) {
    formModel.value.lists.push(list.value)
    list.value = ''
  } else {
    ElMessage.error('请填写数据源')
  }
}
// 计算属性，将字符串数组转换为对象数组
const formattedLists = computed(() => {
  return formModel.value.lists.map((item) => ({ value: item }))
})
// 删除数据源本地
const deleteItem = (item) => {
  // 从 lists 中删除指定的 item
  formModel.value.lists = formModel.value.lists.filter((i) => i !== item)
}
// 向外暴露方法
defineExpose({
  open
})
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="title" width="40%">
    <!-- 任务名字（name）信息（meta）任务提交地址（addr）数据源名称（source_name）传节点编号（node_id） -->
    <el-form
      ref="formRef"
      :model="formModel"
      label-width="120px"
      style="margin-left: 75px"
    >
      <el-form-item label="优先级：" class="form-item">
        <!-- <input v-model="formModel.priority" class="input-field" /> -->
        <el-select
          class="select_box"
          :teleported="false"
          style="width: 150px"
          placeholder="请选择优先级"
          v-model="formModel.priority"
          size="large"
        >
          <el-option
            v-for="item in priorityOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="输入数据源：" class="form-item">
        <div v-if="dialog">
          <el-table :data="formattedLists" :show-header="false" max-height="80">
            <el-table-column
              fixed
              prop="value"
              label="输入数据源"
              width="210"
            />
            <el-table-column fixed="right" label="Operations">
              <template #default="{ row }">
                <!-- 使用 row 访问当前行的数据 -->
                <el-icon size="18" color="red" @click="deleteItem(row.value)">
                  <Delete />
                </el-icon>
              </template>
            </el-table-column>
          </el-table>
          <el-button
            class="mt-4"
            style="width: 100%; background-color: white; color: black"
            @click="onAddItem"
            v-if="isInput"
          >
            <span style="font-size: 20px">+</span>
            <span style="font-size: 12px; font-weight: 700"
              >添加数据源信息</span
            >
          </el-button>
          <el-input
            v-else
            v-model="list"
            autofocus="true"
            style="max-width: 600px"
            placeholder="请输入数据源"
          >
            <template #append>
              <el-button @click="onAdd">添加</el-button>
            </template>
          </el-input>
        </div>

        <el-upload
          v-else
          :on-success="successUpload"
          :http-request="import_Data"
          :before-upload="before_Upload"
          :show-file-list="false"
          style="width: 286.33px; height: 39.33px"
        >
          <el-button
            icon="el-icon-upload2"
            style="width: 286.33px; height: 39.33px"
          >
            <div
              style="display: flex; justify-content: space-between; width: 70px"
            >
              <div>上传文件</div>
              <div>+</div>
            </div>
          </el-button>
        </el-upload>
        <el-switch
          :value="dialog"
          :disabled="formModel.lists.length > 0"
          @change="change()"
          style="margin-left: 20px"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          @click="dialogVisible = false"
          style="margin-left: 165px; margin-bottom: 10px"
          >取消操作</el-button
        >
        <el-button @click="onSubmit" style="margin-left: 122px">{{
          btnMsg
        }}</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style>
.upbox {
  width: 350px;
  display: flex;
  flex-direction: column;
}
.uptitle {
  text-align: center;
  font-size: 20px;
  color: #fff;
  margin-left: 18px;
  margin-bottom: 7px;
}

.upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgb(66, 73, 112);
  border-color: rgb(73, 80, 119);
  color: white;
}

.image-container img {
  width: 70px;
  margin-bottom: 5px;
}

.btupload {
  text-align: center;
  width: 280px;
  height: 150px;
  border: none;
  border-radius: 20px;
  margin-top: 10px;
  margin-left: 50px;
  border: rgb(89, 97, 142) 1px solid;
  background-color: rgb(66, 73, 112);
}

.el-upload__tip {
  color: #999696;
  /* // margin-left: 20px; */
}
.el-dialog {
  /* width: 577px; */
  /* height: 288px; */
  background-color: #313862 !important;
  border-top: 21px solid #5ed1f7;
}
.el-dialog__title {
  font-size: 16px;
  color: #fff;
}
.el-form-item__label {
  font-size: 15px;
  color: #fff;
}

.dialog-footer {
  display: flex;
  margin-top: -30px;
}
.el-button {
  width: 59px;
  height: 50px;
  /* background: #8091a5; */
  background-color: rgb(58, 65, 106);
  color: white;
  border: 1px solid rgba(128, 145, 165, 0.1);
  /* opacity: 0.2; */
}

.el-button:hover {
  color: #fff;
  background: linear-gradient(90deg, #5ed1f7 0%, #4791f3 100%);
  border: 1px solid #4790f3;
}

.input-field {
  padding-left: 10px;
  width: 273px;
  height: 36px;
  background: rgba(0, 0, 0, 0);
  border: 1px solid rgb(58, 65, 106);
  /* opacity: 0.8; */
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 16px;
  color: #8091a5;
  line-height: 24px;
  /* text-align: center; */
  font-style: normal;
  text-transform: none;
  outline: none;
  background-color: rgb(58, 65, 106);
}
</style>
